<template>
  <div id="container">
    <!-- 头部 -->
    <TodoHeader @addTodo="addTodo" />
    <!-- 列表 -->
    <TodoList :todos="todoList" @delTodo="delTodo" />
    <TodoFooter :tabType="tabType" @changeTabType="changeTabType" :count="todoList.length" />
  </div>
</template>

<script>
import TodoFooter from './components/TodoFooter.vue';
import TodoHeader from './components/TodoHeader.vue'
import TodoList from './components/TodoList.vue';

const LOCAL_STOPRAGE_KEY = 'vue-todos';

export default {
  name: 'App',
  components: {
    TodoHeader,
    TodoList,
    TodoFooter
  },
  data() {
    return {
      todos: JSON.parse(localStorage.getItem(LOCAL_STOPRAGE_KEY) || '[]'),
      tabType: 0, // 0:全部，1:未完成，2:已完成
      id: 0
    }
  },

  watch: {
    todos: {
      handler(todos) {
        localStorage.setItem(LOCAL_STOPRAGE_KEY, JSON.stringify(todos));
      },
      deep: true
    }
  },
  created() {

  },

  computed: {
    /**
     * 根据tabType值，计算出需要显示的todoList
     * @returns {Array} 需要显示的todoList
     */
    todoList() {
      if (this.tabType === 0) {
        return this.todos;
      }

      return this.todos.filter(todo => {
        if (this.tabType === 1) {
          return !todo.completed;
        } else {
          return todo.completed;
        }
      })
    }
  },
  methods: {
    addTodo(newTodo) {
      this.todos.push({
        id: +new Date(), // 以当前时间戳 作为id 
        txt: newTodo,
        completed: false
      })
    },

    delTodo(todo) {
      this.todos = this.todos.filter(item => item.id !== todo.id)
    },

    changeTabType(tabType) {
      this.tabType = tabType;
    }
  }
}
</script>

<style>
html,
body {
  background-color: #f5f5f5;
}

#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}

.container {
  max-width: 980px;
  margin-left: 100%;
  margin: 0 auto;
}
</style>
